import { CallHandler } from '@nestjs/common';
/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-08-23 20:31:52
 * @LastEditTime: 2024-08-23 22:59:37
 * @FilePath: /nest_study/server/src/common/decorators/logger-intercaptor.ts
 */
import { Injectable, NestInterceptor, ExecutionContext, Logger } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const start = Date.now(); // 请求开始时间
        const host = context.switchToHttp();
        const request = host.getRequest<Request>();  //  这里可以得到请求的绝大部分信息
        const reqHeaders: any = request.headers  //得到请求头信息
        const urlInfo = `${request.method} ${request.url}`;
        const controllerName = context.getClass().name;
        return next
            .handle()
            .pipe(
                tap(() => {
                    Logger.log(`模块：${controllerName} 请求接口: ${urlInfo}, 响应时间: ${Date.now() - start} ms  请求来源: ${reqHeaders.host}`)
                }
                ),
            );
    }
}